<template>
  <div class="buyer-orders">
    <!-- 顶部导航栏 -->
    <el-header class="header">
      <div class="header-left">
        <h2>我的订单</h2>
      </div>
      <div class="header-right">
        <el-button @click="$router.push('/buyer')">
          <el-icon><ArrowLeft /></el-icon>
          返回商城
        </el-button>
      </div>
    </el-header>

    <!-- 主要内容区域 -->
    <el-main class="main">
      <!-- 用户未登录提示 -->
      <div v-if="!userInfo.id && !userLoading" class="login-tip">
        <el-empty description="请先登录后再查看订单">
          <el-button type="primary" @click="$router.push('/login')">
            去登录
          </el-button>
        </el-empty>
      </div>

      <!-- 订单管理内容 -->
      <div v-else>
        <!-- 订单筛选 -->
        <div class="filter-section">
          <el-select 
            v-model="statusFilter" 
            placeholder="订单状态" 
            style="width: 150px; margin-right: 15px"
            @change="handleStatusFilter"
            :disabled="loading"
          >
            <el-option label="全部订单" value="" />
            <el-option label="待付款" :value="0" />
            <el-option label="待发货" :value="1" />
            <el-option label="已发货" :value="2" />
            <el-option label="已完成" :value="3" />
            <el-option label="已取消" :value="4" />
          </el-select>
          
          <el-input
            v-model="searchKeyword"
            placeholder="搜索订单号或商品名称"
            style="width: 250px; margin-right: 15px"
            @keyup.enter="handleSearch"
            :disabled="loading"
          >
            <template #append>
              <el-button @click="handleSearch" :disabled="loading">
                <el-icon><Search /></el-icon>
              </el-button>
            </template>
          </el-input>
          
          <el-button type="primary" @click="loadOrders" :loading="loading">
            <el-icon><Refresh /></el-icon>
            刷新
          </el-button>
        </div>

        <!-- 订单列表 -->
        <div class="orders-container">
          <!-- 加载状态 -->
          <div v-if="loading" class="loading-container">
            <el-skeleton :rows="3" animated />
          </div>
          
          <!-- 空状态 -->
          <div v-else-if="orders.length === 0" class="empty-orders">
            <el-empty description="暂无订单" />
          </div>
          
          <!-- 订单列表 -->
          <el-card 
            v-else
            v-for="order in orders" 
            :key="order.id" 
            class="order-card"
            shadow="hover"
          >
            <div class="order-header">
              <div class="order-info">
                <span class="order-number">订单号：{{ order.orderNo }}</span>
                <span class="order-time">创建时间：{{ formatTime(order.createTime) }}</span>
              </div>
              <div class="order-status">
                <el-tag :type="getStatusType(order.orderStatus)">
                  {{ getStatusText(order.orderStatus) }}
                </el-tag>
              </div>
            </div>
            
            <div class="order-content">
              <div class="product-info">
                <el-image
                  :src="getProductImage(order.productId)"
                  style="width: 80px; height: 80px; object-fit: cover;"
                  fit="cover"
                />
                <div class="product-details">
                  <h4>{{ order.productName }}</h4>
                  <p class="price">¥{{ order.totalAmount }}</p>
                  <p class="quantity">数量：{{ order.quantity || 1 }}</p>
                </div>
              </div>
              
              <div class="order-actions">
                <el-button 
                  v-if="order.orderStatus === 0" 
                  type="primary" 
                  size="small"
                  @click="handlePay(order.id)"
                >
                  立即付款
                </el-button>
                <el-button 
                  v-if="order.orderStatus === 2" 
                  type="success" 
                  size="small"
                  @click="handleConfirm(order.id)"
                >
                  确认收货
                </el-button>
                <el-button 
                  v-if="order.orderStatus === 0 || order.orderStatus === 1" 
                  type="danger" 
                  size="small"
                  @click="handleCancel(order.id)"
                >
                  取消订单
                </el-button>
                <el-button 
                  type="info" 
                  size="small"
                  @click="showOrderDetail(order)"
                >
                  订单详情
                </el-button>
              </div>
            </div>
          </el-card>
        </div>
      </div>
    </el-main>

    <!-- 订单详情对话框 -->
    <el-dialog
      v-model="showDetailDialog"
      title="订单详情"
      width="600px"
    >
      <div v-if="selectedOrder" class="order-detail">
        <el-descriptions :column="2" border>
          <el-descriptions-item label="订单号">{{ selectedOrder.orderNo }}</el-descriptions-item>
          <el-descriptions-item label="订单状态">
            <el-tag :type="getStatusType(selectedOrder.orderStatus)">
              {{ getStatusText(selectedOrder.orderStatus) }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="商品名称">{{ selectedOrder.productName }}</el-descriptions-item>
          <el-descriptions-item label="订单金额">¥{{ selectedOrder.totalAmount }}</el-descriptions-item>
          <el-descriptions-item label="收货人">{{ selectedOrder.receiverName }}</el-descriptions-item>
          <el-descriptions-item label="联系电话">{{ selectedOrder.receiverPhone }}</el-descriptions-item>
          <el-descriptions-item label="收货地址" :span="2">{{ selectedOrder.receiverAddress }}</el-descriptions-item>
          <el-descriptions-item label="创建时间">{{ formatTime(selectedOrder.createTime) }}</el-descriptions-item>
          <el-descriptions-item label="更新时间">{{ formatTime(selectedOrder.updateTime) }}</el-descriptions-item>
          <el-descriptions-item v-if="selectedOrder.payTime" label="支付时间">{{ formatTime(selectedOrder.payTime) }}</el-descriptions-item>
          <el-descriptions-item v-if="selectedOrder.shipTime" label="发货时间">{{ formatTime(selectedOrder.shipTime) }}</el-descriptions-item>
          <el-descriptions-item v-if="selectedOrder.cancelTime" label="取消时间">{{ formatTime(selectedOrder.cancelTime) }}</el-descriptions-item>
        </el-descriptions>
      </div>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { 
  getOrdersByBuyerId, 
  getOrdersByStatusB, 
  payOrder, 
  confirmOrder, 
  cancelOrder, 
  getOrderById
} from '../api/order.js'
import { getUserInfo } from '../api/user.js'
import { 
  ArrowLeft, 
  Search, 
  Refresh 
} from '@element-plus/icons-vue'

const router = useRouter()

// 响应式数据
const orders = ref([])
const statusFilter = ref('')
const searchKeyword = ref('')
const showDetailDialog = ref(false)
const selectedOrder = ref(null)
const userInfo = ref({})
const loading = ref(false)
const userLoading = ref(false)
const ordersLoading = ref(false)

// 方法
const loadOrders = async () => {
  try {
    ordersLoading.value = true
    // 检查用户信息
    if (!userInfo.value || !userInfo.value.id) {
      orders.value = []
      return
    }
    // 请求订单接口
    const res = await getOrdersByBuyerId(userInfo.value.id)
    if (res && (res.state === 200 || res.code === 200)) {
      // 兼容后端返回结构
      orders.value = Array.isArray(res.data) ? res.data : (res.data?.data || [])
    } else {
      orders.value = []
    }
  } catch (error) {
    orders.value = []
  } finally {
    ordersLoading.value = false
  }
}

const loadUserInfo = async () => {
  try {
    userLoading.value = true
    const res = await getUserInfo()
    if (res && (res.state === 200 || res.code === 200)) {
      userInfo.value = res.data || {}
    }
  } finally {
    userLoading.value = false
  }
}

const handleStatusFilter = () => {
  loadOrders()
}

const handleSearch = () => {
  // 这里可以实现搜索功能，暂时简单过滤
  if (!searchKeyword.value.trim()) {
    loadOrders()
    return
  }
  
  const keyword = searchKeyword.value.toLowerCase()
  orders.value = orders.value.filter(order => 
    order.orderNo?.toLowerCase().includes(keyword) ||
    order.productName?.toLowerCase().includes(keyword)
  )
}

const handlePay = async (orderId) => {
  try {
    await payOrder(orderId)
    await loadOrders()
  } catch (error) {
    console.error('支付失败:', error)
    ElMessage.error('支付失败')
  }
}

const handleConfirm = async (orderId) => {
  try {
    await confirmOrder(orderId)
    await loadOrders()
  } catch (error) {
    console.error('确认收货失败:', error)
    ElMessage.error('确认收货失败')
  }
}

const handleCancel = async (orderId) => {
  try {
    await cancelOrder(orderId)
    await loadOrders()
  } catch (error) {
    console.error('取消订单失败:', error)
    ElMessage.error('取消订单失败')
  }
}

const showOrderDetail = async (order) => {
  try {
    const res = await getOrderById(order.id)
    if (res && (res.state === 200 || res.code === 200)) {
      selectedOrder.value = res.data
      showDetailDialog.value = true
    } else {
      ElMessage.error(res?.message || '获取订单详情失败')
    }
  } catch (error) {
    console.error('获取订单详情失败:', error)
    ElMessage.error('获取订单详情失败')
  }
}

const getStatusType = (status) => {
  const typeMap = {
    0: 'info',    // 待付款
    1: 'warning', // 待发货
    2: 'primary', // 已发货
    3: 'success', // 已完成
    4: 'danger'   // 已取消
  }
  return typeMap[status] || 'info'
}

const getStatusText = (status) => {
  const textMap = {
    0: '待付款',
    1: '待发货',
    2: '已发货',
    3: '已完成',
    4: '已取消'
  }
  return textMap[status] || '未知'
}

const formatTime = (time) => {
  if (!time) return ''
  return new Date(time).toLocaleString('zh-CN')
}

const getProductImage = (productId) => {
  // 假设订单里有 images 字段，否则返回默认图片
  const order = orders.value.find(o => o.productId === productId)
  if (order && order.images) {
    if (order.images.startsWith('http')) return order.images
    return `http://localhost:8080${order.images}`
  }
  return '/default-product.jpg'
}

const testSession = async () => {
  try {
    console.log('开始测试Session...')
    console.log('当前用户信息:', userInfo.value)
    
    // 测试用户信息API
    const userRes = await getUserInfo()
    console.log('用户信息API响应:', userRes)
    
    if (userRes && (userRes.state === 200 || userRes.code === 200)) {
      ElMessage.success('Session正常，用户已登录')
    } else {
      ElMessage.warning('Session可能已失效')
    }
  } catch (error) {
    console.error('Session测试失败:', error)
    ElMessage.error('Session测试失败')
  }
}

// 生命周期
onMounted(async () => {
  console.log('BuyerOrders组件挂载')
  
  // 检查当前路由状态
  console.log('当前路由:', router.currentRoute.value.path)
  
  // 先加载用户信息
  await loadUserInfo()
  
  // 检查用户信息状态
  console.log('用户信息状态:', {
    hasUserInfo: !!userInfo.value,
    hasUserId: !!userInfo.value.id,
    userInfo: userInfo.value
  })
  
  // 只有在用户信息完整时才加载订单
  if (userInfo.value && userInfo.value.id) {
    console.log('用户已登录，加载订单')
    await loadOrders()
  } else {
    console.log('用户未登录或获取用户信息失败，不加载订单')
  }
})
</script>

<style scoped>
.buyer-orders {
  height: 100vh;
  display: flex;
  flex-direction: column;
}

.header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  background: #fff;
  border-bottom: 1px solid #e4e7ed;
  padding: 0 20px;
}

.header-left h2 {
  margin: 0;
  color: #409eff;
}

.main {
  flex: 1;
  padding: 20px;
  background: #f5f7fa;
}

.filter-section {
  background: #fff;
  padding: 20px;
  border-radius: 8px;
  margin-bottom: 20px;
  display: flex;
  align-items: center;
}

.orders-container {
  display: flex;
  flex-direction: column;
  gap: 15px;
}

.empty-orders {
  background: #fff;
  padding: 40px;
  border-radius: 8px;
  text-align: center;
}

.order-card {
  background: #fff;
  border-radius: 8px;
}

.order-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding-bottom: 15px;
  border-bottom: 1px solid #f0f0f0;
}

.order-info {
  display: flex;
  flex-direction: column;
  gap: 5px;
}

.order-number {
  font-weight: bold;
  color: #333;
}

.order-time {
  font-size: 12px;
  color: #999;
}

.order-content {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding-top: 15px;
}

.product-info {
  display: flex;
  align-items: center;
  gap: 15px;
  flex: 1;
}

.product-details h4 {
  margin: 0 0 5px 0;
  color: #333;
}

.price {
  color: #f56c6c;
  font-weight: bold;
  margin: 5px 0;
}

.quantity {
  color: #666;
  font-size: 12px;
  margin: 0;
}

.order-actions {
  display: flex;
  gap: 10px;
}

.order-detail {
  padding: 20px 0;
}

.login-tip {
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 400px;
}

.loading-container {
  padding: 40px;
  background: #fff;
  border-radius: 8px;
}
</style> 